package com.qfedu.empproject.filter;

import com.qfedu.empproject.entity.Manager;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Objects;

@WebFilter("/manager/*")
public class AuthFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // 判断用户是否登录过
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpSession session = req.getSession();
        // 从session中取出来登录的用户
        Manager manager = (Manager) session.getAttribute("loginUser");
        if(Objects.nonNull(manager)){
            // 登陆过
            filterChain.doFilter(servletRequest, servletResponse);
        }else {
            // 没有登录过
            HttpServletResponse resp = (HttpServletResponse) servletResponse;
            // 获取项目名
            String path = req.getContextPath();
            resp.sendRedirect(path+"/index.jsp");
        }
    }

    @Override
    public void destroy() {

    }
}
